/**
 * 我的申请
 */
import React, { Fragment, useEffect } from 'react';
import { connect } from 'umi';
import { Form, Input, TreeSelect, Table, DatePicker, Card } from 'antd';
import xss from 'xss';

import { utils } from 'vv-frontend-components';
import { AdvancedSearch, TableFilter } from '@/components';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import ApplyStatus from '@/components/ApplyStatus';
import LinkTo from '@/components/LinkTo';
import PageRouter from '@/components/PageRouter/PageRouter';
import { getTreeData } from '@/utils/utils';
import { withRoutePage } from '@/utils/enhanceUtils';

const { SHOW_ALL } = TreeSelect;
const { RangePicker } = DatePicker;
const { deepTrim } = utils;

const getData = data => {
    if (!data || data.length === 0) return [];
    return getTreeData(
        data.map(item => ({
            ...item,
            templateName: item.category,
            children: item.templateList || []
        })),
        {
            title: 'templateName',
            value: 'templateName'
        }
    );
};

const transformFilters = (data = []) =>
    data.map(item => ({
        text: item.dictName,
        value: item.dictValue
    }));

const columns = processStatusType => [
    {
        title: '申请主题',
        dataIndex: 'applicationName',
        key: 'applicationName',
        render: (text, record) => (
            <span>
                {record.status === '1' ? (
                    <LinkTo
                        to="/personal/portal/flow/mine/list/apply"
                        query={{
                            formDeploymentId: record.formDeploymentId,
                            id: record.id,
                            processDeploymentId: record.processDeploymentId,
                            templateId: record.templateId,
                            templateName: record.templateName,
                            applicationNo: record.applicationNo
                        }}
                    >
                        {text}
                    </LinkTo>
                ) : (
                    <LinkTo
                        to="/personal/portal/flow/mine/myApplication/detail"
                        query={{
                            applicationNo: record.applicationNo
                        }}
                    >
                        {text}
                    </LinkTo>
                )}
            </span>
        )
    },
    {
        title: '申请单摘要',
        width: 400,
        dataIndex: 'applicationNote',
        key: 'applicationNote',
        render(text) {
            return (
                <div
                    style={{
                        display: '-webkit-box',
                        WebkitLineClamp: 5,
                        overflow: 'hidden',
                        maxHeight: 105,
                        WebkitBoxOrient: 'vertical'
                    }}
                >
                    <span style={{ wordBreak: 'break-all' }} dangerouslySetInnerHTML={{ __html: xss(text) }} />
                </div>
            );
        }
    },
    {
        title: '发起时间',
        dataIndex: 'startTime',
        key: 'startTime',
        sorter: () => {}
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'states',
        filters: transformFilters(processStatusType),
        filterDropdown: filterProps => <TableFilter {...filterProps} />,
        filterMultiple: false,
        width: 150,
        render: (text, record) => {
            const find = processStatusType.find(item => `${item.dictValue}` === text);
            const name = find ? find.dictName : '';
            if (text === '1' || text === '4' || text === '5') {
                return (
                    <div>
                        <ApplyStatus status={record.status} />
                        {name}
                    </div>
                );
            }
            return (
                <div>
                    <ApplyStatus status={record.status} />
                    {record.candidateUsers}-{name}
                </div>
            );
        }
    }
];

const List = ({ form, myapply, loading, dispatch }) => {
    const { getFieldsValue, getFieldDecorator } = form;
    const { pagination, data, flowType = [], processStatusType = [] } = myapply;

    const fetchList = () => {
        const { title = '', date = [], templateNameList = [] } = getFieldsValue();
        dispatch(
            deepTrim({
                type: 'myapply/fetchList',
                payload: {
                    title,
                    status: myapply.status,
                    startTime: date[0] ? date[0].format('YYYY-MM-DD 00:00:00') : '',
                    endTime: date[1] ? date[1].format('YYYY-MM-DD 23:59:59') : '',
                    templateNameList,
                    pageNo: pagination.current,
                    pageSize: pagination.pageSize,
                    orderBy: myapply.orderBy
                }
            })
        );
    };

    const handleSubmit = async () => {
        if (pagination.current !== 1) {
            await dispatch({
                type: 'myapply/save',
                payload: {
                    pagination: {
                        ...pagination,
                        current: 1
                    }
                }
            });
        } else {
            fetchList();
        }
    };

    const tableChange = (_pagination, filters = {}, sorter) => {
        let status = '';
        let orderBy = '';
        if (filters && filters.states && filters.states.length > 0) {
            // eslint-disable-next-line prefer-destructuring
            status = filters.states[0];
        }
        if (sorter && sorter.field === 'startTime') {
            orderBy = 'starting_time ';
            orderBy += sorter.order === 'ascend' ? 'asc' : 'desc';
        }
        dispatch({
            type: 'myapply/save',
            payload: {
                status,
                orderBy,
                pagination: { ...pagination, current: 1 }
            }
        });
    };
    const paginationChange = _pagination => {
        dispatch({ type: 'myapply/save', payload: { pagination: { ...pagination, ..._pagination } } });
    };

    useEffect(() => {
        dispatch({
            type: 'myapply/fetchFlowType',
            payload: {
                code: 'flowType',
                isShowChildFormat: 1
            }
        });
        dispatch({
            type: 'myapply/fetchProcessStatusType',
            payload: {
                code: 'processStatusType'
            }
        });

        return () => {
            dispatch({
                type: 'myapply/save',
                payload: {
                    orderBy: '',
                    status: '',
                    pagination: {
                        ...pagination,
                        current: 1,
                        pageSize: 10
                    }
                }
            });
        };
    }, []);

    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [myapply.orderBy, myapply.status, pagination.pageSize, pagination.current]);

    return (
        <PageHeaderWrapper>
            <PageRouter type="myflow">
                {isPageRouter => (
                    <Fragment>
                        <Card bordered={false} title={!isPageRouter && '我的申请'}>
                            <AdvancedSearch onReset={handleSubmit} onSubmit={handleSubmit} form={form}>
                                <Form.Item label="标题">
                                    {getFieldDecorator('title')(<Input placeholder="请输入主题" allowClear />)}
                                </Form.Item>
                                <Form.Item label="发起时间">{getFieldDecorator('date')(<RangePicker />)}</Form.Item>
                                <Form.Item label="申请类型">
                                    {getFieldDecorator('templateNameList')(
                                        <TreeSelect
                                            maxTagCount={2}
                                            treeCheckable
                                            showCheckedStrategy={SHOW_ALL}
                                            searchPlaceholder="请选择"
                                            treeData={getData(flowType)}
                                            allowClear
                                        />
                                    )}
                                </Form.Item>
                            </AdvancedSearch>
                            <Table
                                bordered={false}
                                columns={columns(processStatusType)}
                                loading={loading.models.myapply}
                                dataSource={data}
                                onChange={tableChange}
                                rowKey="id"
                                pagination={false}
                            />
                            <Pagination {...pagination} onChange={paginationChange} />
                        </Card>
                    </Fragment>
                )}
            </PageRouter>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(connect(({ myapply, loading }) => ({ myapply, loading }))(Form.create()(List)));
